package top.banner.contentcenter;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import top.banner.contentcenter.dao.share.ShareMapper;
import top.banner.contentcenter.domain.dto.user.UserDTO;
import top.banner.contentcenter.domain.entity.share.Share;
import top.banner.contentcenter.feignclient.TestBaiduFeignClient;
import top.banner.contentcenter.feignclient.TestUserCenterFeignClient;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
public class TestController {
    @Resource
    private ShareMapper shareMapper;
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/test")
    public List<Share> testInsert() {
        // 1. 做插入
        Share share = new Share();
        share.setCreateTime(new Date());
        share.setUpdateTime(new Date());
        share.setTitle("xxx");
        share.setCover("xxx");
        share.setAuthor("大目");
        share.setBuyCount(1);

        this.shareMapper.insertSelective(share);

        // 2. 做查询: 查询当前数据库所有的share  select * from share ;

        return this.shareMapper.selectAll();
    }

    /**
     * 测试：服务发现，证明内容中心总能找到用户中心
     *
     * @return 用户中心所有实例的地址信息
     */
    @GetMapping("/test2")
    public List<ServiceInstance> getInstances() {
        // 查询指定服务的所有实例的信息
        // consul/eureka/zookeeper...
        return this.discoveryClient.getInstances("user-center");
    }

    @Resource
    private TestUserCenterFeignClient testUserCenterFeignClient;

    @GetMapping("/test-get")
    public UserDTO query(UserDTO userDTO) {
        return testUserCenterFeignClient.query(userDTO);
    }


    @Resource
    private TestBaiduFeignClient testBaiduFeignClient;

    @GetMapping("/baidu")
    public String baidu() {
        return testBaiduFeignClient.index();
    }


    @Resource
    private TestService testService;

    @GetMapping("/test-a")
    public String testA() {
        testService.common();
        return "test-a";
    }

    @GetMapping("/test-b")
    public String testB() {
        testService.common();
        return "test-b";
    }

    @GetMapping("test-hot")
    @SentinelResource("hot")
    public String testHot(@RequestParam(required = false) String a,
                          @RequestParam(required = false) String b) {
        return a + " " + b;
    }


    /**
     * 通过代码配置流控规则
     */
    @GetMapping("test-add-flow-rule")
    public String testHot() {
        this.initFlowQpsRule();
        return "success";
    }

    private void initFlowQpsRule() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule("/shares/1");
        // set limit qps to 20
        rule.setCount(20);
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setLimitApp("default");
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }


    @GetMapping("/test-sentinel-api")
    public String testSentinelAPI(@RequestParam(required = false) String a) {
        String resourceName = "test-sentinel-api";

        //针对来源
        ContextUtil.enter(resourceName, "test-wfw");

        //定义一个sentinel保护的资源
        Entry entry = null;
        try {
            entry = SphU.entry(resourceName);
            //被保护的业务逻辑
            if (StringUtils.isBlank(a)) {
                //抛出的异常，不会被加降级规则中的异常数统计到，要通过Tracer.trace去统计
                throw new IllegalArgumentException("a不能为空");
            }
            return a;
        } catch (BlockException e) {
            //如果被保护的资源被限流或者降级，就会抛出BlockException
            log.warn("限流，或者降级了", e);
            return "限流，或者降级了";
        } catch (IllegalArgumentException e2) {
            //统计Throwable【发生的次数和占比】
            Tracer.trace(e2);
            return "参数错误";
        } finally {
            if (entry != null) {
                //退出 entry
                entry.exit();
            }
            ContextUtil.exit();
        }


    }

    @GetMapping("/test-sentinel-resource")
    @SentinelResource(value = "test-sentinel-resource",
            blockHandler = "block",
            fallback = "fallback")
    public String testSentinelResource(@RequestParam(required = false) String a) {

        //被保护的业务逻辑
        if (StringUtils.isBlank(a)) {
            //抛出的异常，不会被加降级规则中的异常数统计到，要通过Tracer.trace去统计
            throw new IllegalArgumentException("a cannot be blank");
        }
        return a;

    }


    /**
     * 处理限流或者降级
     */
    public String block(String a, BlockException e) {
        //如果被保护的资源被限流或者降级，就会抛出BlockException
        log.warn("限流，或者降级了", e);
        return "限流，或者降级了 block";
    }

    /**
     * 处理降级
     * - 1.6 以后 处理异常
     */
    public String fallback(String a) {
        //如果被保护的资源被限流或者降级，就会抛出BlockException
        return "限流，或者降级了 fallback";
    }


    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/test-rest-template-sentinel/{userId}")
    public UserDTO test(@PathVariable Integer userId) {
        return restTemplate.getForObject("http://user-center/users/{userId}", UserDTO.class, userId);
    }


    @Resource
    private Source source;

    @GetMapping("/test-stream")
    public String testStream() {
        source.output()
                .send(
                        MessageBuilder.withPayload("消息体").build()
                );
        return "success";
    }

}